import { ArgumentMetadata, Injectable, PipeTransform, BadRequestException } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';

@Injectable()
export class ClassValidPipe implements PipeTransform {
  async transform(value: any, metadata: ArgumentMetadata) {
    const { metatype } = metadata;
    console.log('metadata :>> ', metadata);
    if (!metatype || !this.toValidate(metatype)) {
      console.log('IF :>> ', metatype);
      console.log('toValidate :>> ', this.toValidate(metatype));
      return value;
    }
    //生成对应类型的对象
    const object = plainToInstance(metatype, value);
    console.log('object :>> ', object);
    //利用dto中规则对数据进行验证
    const error = await validate(object);
    console.log('error :>> ', error);
    if (error.length > 0) {
      throw new BadRequestException(error);
    }
    return value;
  }

  private toValidate(metatype: Function): boolean {
    const types: Function[] = [String, Boolean, Number, Array, Object];
    return !types.includes(metatype);
  }
}
